package org.rssReader;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;


import org.apache.log4j.Logger;
import org.jdom.JDOMException;
import org.rssReader.model.Model;


import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

public class RssReader {

	private String feedUrl;
	private Model model;
	private static final Logger logger = Logger.getLogger(RssReader.class);
	public RssReader(String url){
		feedUrl = url;
		model = Model.getInstance();
	}
	
	/**
	 * Gets the rss feed
	 * @return
	 */
	public String getFeed() {
		logger.debug("---------------------------");
		logger.debug("----Starting analyzing-----");
		logger.debug("---------------------------");
		URL url = null;
		SyndFeed feed = null;
		try {
			url = new URL(feedUrl);
			SyndFeedInput input = new SyndFeedInput();
	        XmlReader doc = null;
	        doc = new XmlReader(url);
	        feed = input.build(doc);
		} catch (MalformedURLException e) {
			logger.error("MalformedURLException error in getFeed:", e);
		} catch (IOException e) {
			logger.error("IOException error in getFeed:", e);
		} catch (IllegalArgumentException e) {
			logger.error("IllegalArgumentException error in getFeed:", e);
		} catch (FeedException e) {
			logger.error("FeedException error in getFeed:", e);
		}
		logger.debug(getTitles(feed));
		logger.debug("---------------------------");
		logger.debug("-----Analyzing ended-------");
		logger.debug("---------------------------");
		return feed.toString();
	}
	
	private String getTitles(SyndFeed feed){
		StringBuilder sb = new StringBuilder();
		List<SyndEntry> entries = feed.getEntries();
		try {
			SettingsReader sr= new SettingsReader("settings\\settings.xml");
			sr.getShwos();
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			logger.error("JDOMException error in getTitles:", e);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			//logger.debug("IOException error in getTitles:");
			logger.error("IOException error in getTitles:", e);
		} 
		for (SyndEntry entry : entries) {
			String title = entry.getTitle();
			for(int  i =0;i<model.getShowsList().size();i++){
				if(title.toLowerCase().contains(model.getShow(i).toLowerCase())){
					for(int j = 0;j<model.getRegexes().size();j++){
						LinksParser.getLinks(model.getRegexes().get(j), entry.getDescription().getValue());
					}
				}
			}
			sb.append(entry.getTitle() + "\n");
		}
		
		return sb.toString();
	}
}
